import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Drawer } from 'antd';
import { FlowDebugRecordInfoResponse, RecordListInfo } from 'admin/schema/FlowDebugRecord';
import { Chat, ChatMessage } from 'components/Chat';
import { getFlowDebugRecordInfo } from 'admin/servers/servers';

interface Iprops {
  visible: boolean; // 窗口显示隐藏
  flowDedugRecordId: string; // 外部数据
  onClose: () => void; // 对话框关闭时的回调
}

const FlowDebugRecordDetail: React.FC<Iprops> = (props: Iprops) => {
  const chatRef = useRef<any>();
  const { flowDedugRecordId } = props;
  const [recordInfo, setRecordInfo] = useState<FlowDebugRecordInfoResponse>({});

  const initData = useCallback(async () => {
    try {
      const { data } = await getFlowDebugRecordInfo(flowDedugRecordId);
      if (data && data.recordList) {
        setRecordInfo(data);
        const list = dataHandler(data.recordList).reverse();
        chatRef.current.setRecord(list);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [flowDedugRecordId]);
  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 将后端返回的数据处理为Chat控件所需要的数据
   */
  function dataHandler(listInfo: RecordListInfo[]): ChatMessage[] {
    const roleMap = ['called', 'caller', 'man'];
    return listInfo.map((item, i) => {
      return {
        index: item.index,
        sound: item.url,
        message: item.text,
        role: roleMap[item.role] as 'called' | 'caller' | 'man',
        status: item.status,
      };
    });
  }

  return (
    <Drawer
      width={500}
      title="详情"
      visible={props.visible}
      footer={null}
      mask={true}
      destroyOnClose={true}
      onClose={() => {
        props.onClose();
      }}
    >
      <div>
        <Chat
          key={flowDedugRecordId}
          showHeadBar={true}
          talkRecord={recordInfo.url ? (process.env.REACT_APP_API_URL || '') + recordInfo.url : ''}
          showStatusHeader={false}
          ref={chatRef}
          callRecordId={flowDedugRecordId}
        />
      </div>
    </Drawer>
  );
};

export default FlowDebugRecordDetail;
